from django_filters import rest_framework as filters
from rest_framework.generics import CreateAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import GenericViewSet, ModelViewSet, mixins
from rest_framework import filters as f
from company.models import Company, Driver, Vehicle, VehicleCompanyTerminal
from company.serializers import (CompanySerializer, DriverSerializer,
                                 VehicleCompanyTerminalSerializer,
                                 VehicleCreateSerializer, VehicleSerializer,
                                 VehicleTerminalSerializer)


class CompanyViewSet(ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer
    filter_fields = ('id', 'name', 'fullname', 'unified_social_credit_code')
    search_fields = ('name', 'fullname')


class DriverSearchFilters(f.SearchFilter):
    def filter_queryset(self, request, queryset, view):
        if request.query_params.get("search", "") == "":
            return queryset
        return super(DriverSearchFilters, self).filter_queryset(request, queryset, view)


class DriverViewSet(mixins.ListModelMixin,
                    GenericViewSet):
    queryset = Driver.objects.all()
    serializer_class = DriverSerializer
    filter_backends = [DriverSearchFilters]
    search_fields = ('name', )


class VehicleViewSet(mixins.ListModelMixin, mixins.CreateModelMixin,
                     GenericViewSet):
    queryset = Vehicle.objects.all()
    serializer_class = VehicleSerializer
    filter_fields = ('id', 'license_number')


class VehicleTerminalFilter(filters.FilterSet):
    license_number = filters.CharFilter(field_name='vehicle__license_number')

    class Meta:
        model = VehicleCompanyTerminal
        exclude = ()


class VehicleSearchFilters(f.SearchFilter):
    def filter_queryset(self, request, queryset, view):
        if request.query_params.get("search", "") == "":
            # 获取所有的车辆信息
            return queryset
        return super(VehicleSearchFilters, self).filter_queryset(request, queryset, view)


class VehicleTerminalViewSet(mixins.ListModelMixin,
                             GenericViewSet):
    queryset = VehicleCompanyTerminal.objects.all()
    serializer_class = VehicleTerminalSerializer
    filter_backends = [VehicleSearchFilters]
    search_fields = ('vehicle__license_number',)

    def get_queryset(self):
        company = self.request.user.company
        return VehicleCompanyTerminal.objects.filter(company=company)


class VehicleCompanyTerminalViewSet(mixins.RetrieveModelMixin,
                                    mixins.CreateModelMixin,
                                    mixins.ListModelMixin,
                                    GenericViewSet):
    queryset = VehicleCompanyTerminal.objects.all()
    serializer_class = VehicleCompanyTerminalSerializer
    search_fields = ('vehicle_id', 'company_id', 'terminal_id')
